package me.zhengjie.modules.quartz.task.processing;

import com.google.common.collect.Lists;
import com.qiaofang.applet.service.other.util.DateTypeUtil;
import com.qiaofang.applet.service.property.service.SyncDataLogService;
import com.qiaofang.applet.service.property.service.dto.CountSynDataListDto;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.task.dingdingUtil.DingdingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author: youqing.yang
 * @Create: 2020/11/11 17:25
 * @Description:
 **/
@Slf4j
@Component
public class SynchronousCountDingdingTask {

    @Autowired
    private SyncDataLogService syncDataLogService;

    public static final String DINGDING_URL = "https://oapi.dingtalk.com/robot/send?access_token=2804fc9c3dc211cc40f40d5db09a267960d2b1a2fdf02f752ae1bbec0ed8744b";

    public static final String SECRET = "SEC772fd459cbd69347e0f09544b2443ed0e5f319569a0ae001406a8d8dd9e54416";

    public void sentDingdingMsg(){

        try {
            List<CountSynDataListDto> listDtos = syncDataLogService.countDailyData(getDayZero(new Date()));

            StringBuffer sb = new StringBuffer();
            Date newDate = new Date();
            Date date = DateTypeUtil.getBeginOrAfterDay(newDate, Calendar.DAY_OF_WEEK, -1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY/MM/dd");
            String yesterday = simpleDateFormat.format(date);

            sb.append(yesterday + "\n小程序同步数据统计：\n");
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(2);
            for (CountSynDataListDto dto : listDtos) {
                if (dto.getPullCount() == 0){
                    sb.append("\n “" + dto.getSynchronousType() + "” | 当日暂无数据更新");
                } else {
                    sb.append("\n “" + dto.getSynchronousType() + "” | 同步成功率"
                            + numberFormat.format((float) dto.getResolveCount() / (float) dto.getPullCount() * 100)
                            + "% ( " + dto.getResolveCount() + "/" + dto.getPullCount() + ")");
                }
            }
            String text = sb.toString();
            DingdingUtil.send(DINGDING_URL, SECRET, text, Lists.newArrayList());
        } catch (Exception e) {
            log.error("钉钉消息发送失败 {}", e);
        }
    }

    private Date getDayZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
}
